package com.cgq.pro.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.cgq.base.action.BaseAction;
import com.cgq.pro.entity.Attachment;
import com.cgq.pro.entity.Land;
import com.cgq.pro.entity.LandForm;
import com.cgq.pro.service.AttachmentService;
import com.cgq.pro.service.LandService;
import com.cgq.utils.CommonUtils;
import com.cgq.utils.GlobalContext;
import com.cgq.utils.IdGenerator;
import com.cgq.utils.PropertiesUtil;

@Controller
public class LandAction  extends BaseAction {
	private String viewType;
	private Land land;
	private String ids;
	private LandForm landForm;

	private File file;
	private String fileFileName;
	private String fileContentType;
	private String fileRemark;
	private String realName;
	private String regionId;
	private String startDate;
	private String endDate;
	/**经度*/
	private String lon;
	/**纬度*/
	private String lat;

	private List<Attachment> attachments;
	private Attachment attachment;

	@Autowired
	private AttachmentService attachmentService;

	@Autowired
	private LandService landService;

	private Map<Integer, String> useTypes=new HashMap<Integer, String>();
	private Map<String, String> areas=new HashMap<String,String>();
	
	public String getViewType() {
		return viewType;
	}
	public void setViewType(String viewType) {
		this.viewType = viewType;
	}
	public Land getLand() {
		return land;
	}
	public void setLand(Land land) {
		this.land = land;
	}
	public Map<Integer, String> getUseTypes() {
		return useTypes;
	}
	public void setUseTypes(Map<Integer, String> useTypes) {
		this.useTypes = useTypes;
	}
	public Map<String, String> getAreas() {
		return areas;
	}
	public void setAreas(Map<String, String> areas) {
		this.areas = areas;
	}
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public LandForm getLandForm() {
		return landForm;
	}
	public void setLandForm(LandForm landForm) {
		this.landForm = landForm;
	}

	public String getFileRemark() {
		return fileRemark;
	}
	public void setFileRemark(String fileRemark) {
		this.fileRemark = fileRemark;
	}
	public String getRealName() {
		return realName;
	}
	public void setRealName(String realName) {
		this.realName = realName;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	public List<Attachment> getAttachments() {
		return attachments;
	}
	public void setAttachments(List<Attachment> attachments) {
		this.attachments = attachments;
	}
	public Attachment getAttachment() {
		return attachment;
	}
	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
	}
	public String getRegionId() {
		return regionId;
	}
	public void setRegionId(String regionId) {
		this.regionId = regionId;
	}
	
	public String getStartDate() {
		return startDate;
	}
	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}
	public String getEndDate() {
		return endDate;
	}
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}
	public String getLon() {
		return lon;
	}
	public void setLon(String lon) {
		this.lon = lon;
	}
	public String getLat() {
		return lat;
	}
	public void setLat(String lat) {
		this.lat = lat;
	}
	/**
	 * 用地计划列表
	 * @return
	 */
	public String gotoLandPlanList(){
		areas=landService.getArea();
		permissionId=getCurrentUser().getPerId().getPerFlag();
		return GlobalContext.RESULT_LPLIST;
	}
	/**
	 * 土地出让
	 * @return
	 */
	public String gotoLandGrantList(){
		areas=landService.getArea();
		permissionId=getCurrentUser().getPerId().getPerFlag();
		return GlobalContext.RESULT_LGLIST;
	}

	/**
	 * 土地成交
	 * @return
	 */
	public String gotoLandTranList(){
		areas=landService.getArea();
		permissionId=getCurrentUser().getPerId().getPerFlag();
		return GlobalContext.RESULT_LTLIST;
	}
	/**
	 * 用地计划form
	 * @return
	 */
	public String gotoLandPlanForm(){
		useTypes=landService.getLandUseType();
		areas=landService.getArea();
		if(GlobalContext.RESULT_ADD.equals(viewType)){
			land=new Land();	
		}else {
			land=landService.find(land.getId());
		}
		return GlobalContext.RESULT_LPFORM;
	}

	/**
	 * 土地出让form
	 * @return
	 */
	public String gotoLandGrantForm()
	{
		useTypes=landService.getLandUseType();
		areas=landService.getArea();
		if(GlobalContext.RESULT_ADD.equals(viewType))
		{
			land=new Land();	
		}else {
			land=landService.find(land.getId());
		}
		return GlobalContext.RESULT_LGFORM;
	}

	public String gotoLandAtta(){
		return "gotoLandAtta";
	}

	public void saveAtta() {
		try {
			String rootpath = getRootPath();
			File path = new File(rootpath + "upload/"
					+ land.getId() + "/");
			if (!path.exists()) {
				path.mkdirs();
			}

			String fullFileName = path + "/" + fileFileName;
			String filePath = "upload/" + land.getId() + "/"
					+ fileFileName;
			FileUtils.copyFile(file, new File(fullFileName));
			Attachment entity=new Attachment();

			entity.setDateCre(new Date());
			entity.setExtName(CommonUtils.getFileExt(fileFileName));
			entity.setFilePath(filePath);
			entity.setFileSize(file.length());
			entity.setName(realName);
			entity.setOriginalName(fileFileName);
			entity.setLand_Id(land.getId());
			entity.setRemark(fileRemark);
			attachmentService.save(entity);
			ajaxDoneSuccess("上传成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String gotoLandTranForm()
	{
		useTypes=landService.getLandUseType();
		areas=landService.getArea();
		if(GlobalContext.RESULT_ADD.equals(viewType))
		{
			land=new Land();	
		}else {
			land=landService.find(land.getId());

		}
		return GlobalContext.RESULT_LTFORM;
	}
	/**
	 * 用地计划的保存
	 */
	public void savePlanLand(){
		try {
			Date date = new Date();
			land.setLat(Double.valueOf(lat));
			land.setLng(Double.valueOf(lon));
			if(GlobalContext.RESULT_ADD.equals(viewType))//保存
			{
				if(land.getType()==1)
					land.setId(IdGenerator.getId(service,"FD_LAND", "PL", 10));
				else  if(land.getType()==2){
					land.setId(IdGenerator.getId(service,"FD_LAND", "GL", 10));	
				}else if(land.getType()==3)
				{
					land.setId(IdGenerator.getId(service,"FD_LAND", "TL", 10));		
				}
				land.setStatus(1);
				land.setDateUpd(land.getDateCre());
				land.setUserCre(getCurrentUser().getName());
				landService.save(land);
				ajaxDoneSuccess("保存成功");
			}else{
				land.setDateUpd(date);
				land.setUserUpd(getCurrentUser().getName());
				landService.update(land);
				ajaxDoneSuccess("更新成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			ajaxDoneSuccess("保存失败");
		}
	}

	public String gotoAttachList(){
		return "attachList";
	}

	/**
	 * 下载文件
	 */
	public void downFile(){
		viewOrDown(true);
	}
	
	/**
	 * 浏览文件
	 */
	public void viewFile(){
		viewOrDown(false);
	}
	
	/**
	 * 下载文件或在线浏览文件操作
	 * @param type true时为下载文件，false为在线浏览文件
	 */
	private void viewOrDown(boolean type){
		attachment=attachmentService.find(attachment.getId());
		FileInputStream fos=null;
		try{
			String rootpath = getRootPath();
			File path = new File(rootpath + attachment.getFilePath());
			fos=new FileInputStream(path);

			HttpServletResponse response=ServletActionContext.getResponse();
			response.reset();
		
			response.setCharacterEncoding("UTF-8");
			if(type){
				response.setHeader("Content-Disposition", "attachment;filename="+new String((attachment.getName()+"."
						+attachment.getExtName()).getBytes(),"UTF-8"));
				response.setContentType("application/octet-stream");
			}else{
				if("xls".equals(attachment.getExtName()) || "xlsx".equals(attachment.getExtName())){
					response.setContentType("application/vnd.ms-excel");
					response.setHeader("Content-Disposition", "inline;filename="
					+URLEncoder.encode(attachment.getOriginalName(),"utf-8"));
				}else if("doc".equals(attachment.getExtName()) || "docx".equals(attachment.getExtName())){
					response.setContentType("application/msword");
					response.setHeader("Content-Disposition", "inline;filename="
					+URLEncoder.encode(attachment.getOriginalName(),"utf-8"));
				}
			}
			
			OutputStream out=response.getOutputStream();
			byte[] b=new byte[1024];
			while(fos.read(b)!=-1){
				out.write(b);
			}
			fos.close();
			out.flush();
			out.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String getAttachList(){
		land=landService.find(land.getId());
		attachments=land.getAttachments();
		int total=attachments.size();
		// 当前页
		int intPage = Integer
				.parseInt((page == null || page == "0") ? "1"
						: page);
		// 每页显示条数
		int number = Integer
				.parseInt((rows == null || rows == "0") ? "5"
						: rows);

		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		attachments=attachments.subList((intPage-1)*number, intPage*number>attachments.size()?attachments.size():intPage*number);
		for(int i=0;i<attachments.size();i++){
			Attachment ment=attachments.get(i);
			Map<String, Object> m = new HashMap<String, Object>();	
			m.put("id", ment.getId());
			m.put("name", ment.getName());
			m.put("remark", ment.getRemark());
			m.put("ope", "<a href=\"javascript:void(0);\" onclick=\"downFile(this,'"+ment.getId()+"')\">下载</a>");
			maps.add(m);

		}
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("total", total);
		json.put("rows", maps);
		resultObj = JSONObject.fromObject(json);
		return "success";
	}
	public String getAllRecords() {
		// 当前页
		int intPage = Integer
				.parseInt((page == null || page == "0") ? "1": page);
		// 每页显示条数
		int number = Integer
				.parseInt((rows == null || rows == "0") ? "5"
						: rows);
		// 每页的开始记录 第一页为1 第二页为number +1
		int start = (intPage - 1) * number;
		
		Map<String, String> map=null;
		if(GlobalContext.RESULT_QUERY.equals(viewType)){ //如果执行查询操作
	        map=new HashMap<String, String>();
	        map.put("regionId", regionId);
	        map.put("startDate", startDate);
        	map.put("endDate",endDate);
        	viewType="";
	    } 	
		int total = landService.getTotal(map,land.getType());
		List<Land> list = landService.getAllRecords(start, number, map, land.getType());
		List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
		for (Land land : list) {
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("id", land.getId());
			m.put("num", land.getNum());
			m.put("name", land.getName());
			m.put("location", land.getLocation());
			try{
				m.put("purpose", PropertiesUtil.readByKey("landUseType", "type."+land.getUseType()));
			}catch(Exception e){
				e.printStackTrace();
			}
			m.put("square", land.getSellArea());
			m.put("target", land.getQuote());

			m.put("remark", land.getRemark());

			if(land.getRegion()!=null)
				m.put("area", land.getRegion().getName());
			m.put("point", land.getPoint());
			m.put("start_price", land.getTransPrice());

			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");

			if(land.getList_date()!=null)
				m.put("list_date", df.format(land.getList_date()));

			m.put("capacity", land.getCapacity());
			m.put("initPrice", land.getInitPrice());
			if(land.getTransDate()!=null)
				m.put("transDate", df.format(land.getTransDate()));
			m.put("transPrice", land.getTransPrice());
			m.put("bidder", land.getBidder());

			if(land.getAttachments()!=null&&land.getAttachments().size()>0)
				m.put("attach", "<a href=\"javascript:void(0);\" onclick=\"viewAttas(this,'"+land.getId()+"')\">查看</a>");
			else {
				m.put("attach", "");
			}
			maps.add(m);
		}
		Map<String, Object> json = new HashMap<String, Object>();
		json.put("total", total);
		json.put("rows", maps);
		resultObj = JSONObject.fromObject(json);
		return "success";
	}
	/**
	 * 删除数据
	 * @throws Exception 
	 */
	public void delete() throws Exception{
		try {
			String[] idList=ids.split(",");
			landService.delete(idList);
			ajaxDoneSuccess("删除成功");
		} catch (Exception e) {
			ajaxDoneSuccess("删除失败");
		}
	}
	public  void deleteAtta() throws Exception{
		try{
			String[] idList=ids.split(",");
			String path = getRootPath();
			attachmentService.deleteAndAttachment(idList, path);
			ajaxDoneSuccess("删除成功");
		}catch(Exception e){
			ajaxDoneSuccess("删除失败");
		}
	}
	public String getAjaxLand(){
		List<Land> list=landService.getAllRecords(landForm);
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter out;
		StringBuffer sb=new StringBuffer();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String sval="";
		for(int i=0;i<list.size();i++){
			Land land=list.get(i);
			sb.append(land.getLng()+"*"+land.getLat()
					+"*"+land.getName()+"*"+land.getLandType()
					+"*"+land.getPoints()+"*"+land.getType()+"*");
			if(land.getType()==1){
				sval="<table>"+
						"<tr><td colspan='2'>坐落位置："+land.getLocation()+"</td></tr>"+
						"<tr><td style='width:150px;'>所属区位："+land.getRegion().getName()+"</td>"+
						"<td style='width:150px;'>土地用途："+land.getUseType()+"</td></tr>"+
						"<tr><td style='width:150px;'>出让面积："+land.getSellArea()+"</td>"+
						"<td style='width:150px;'>规划指标："+land.getQuote()+"</td></tr>"+
						"<tr><td style='width:150px;'>创建时间："+sdf.format(land.getDateCre())+"</td>"+
						"<td style='width:150px;'>创建人："+land.getUserCre()+"</td></tr>"+
						"<tr><td colspan='2'>备注："+land.getRemark()+"</td></tr>"
						+"</table>";
			}else if(land.getType()==2){
				sval="<table>"+
						"<tr><td colspan='2'>坐落位置："+land.getLocation()+"</td></tr>"+
						"<tr><td style='width:150px;'>所属区位："+land.getRegion().getName()+"</td>"+
						"<td style='width:150px;'>土地用途："+land.getUseType()+"</td></tr>"+
						"<tr><td style='width:150px;'>出让面积："+land.getSellArea()+"</td>"+
						"<td style='width:150px;'>地块要点："+land.getPoint()+"</td></tr>"+
						"<tr><td style='width:150px;'>挂牌起始价格："+land.getStart_price()+"</td>"+
						"<td style='width:150px;'>挂牌时间："+sdf.format(land.getList_date())+"</td></tr>"+
						"<tr><td style='width:150px;'>创建时间："+sdf.format(land.getDateCre())+"</td>"+
						"<td style='width:150px;'>创建人："+land.getUserCre()+"</td></tr>"+
						"<tr><td colspan='2'>备注："+land.getRemark()+"</td></tr>"
						+"</table>";
			}else{
				sval="<table>"+
						"<tr><td colspan='2'>坐落位置："+land.getLocation()+"</td></tr>"+
						"<tr><td style='width:150px;'>所属区位："+land.getRegion().getName()+"</td>"+
						"<td style='width:150px;'>土地用途："+land.getUseType()+"</td></tr>"+
						"<tr><td style='width:150px;'>土地面积："+land.getSellArea()+"</td>"+
						"<td style='width:150px;'>容积率："+land.getCapacity()+"</td></tr>"+
						"<tr><td style='width:150px;'>起始价格："+land.getInitPrice()+"</td>"+
						"<td style='width:150px;'>成交价格："+land.getTransPrice()+"</td></tr>"+
						"<tr><td style='width:150px;'>成交日期："+sdf.format(land.getTransDate())+"</td>"+
						"<td style='width:150px;'>竞得人："+land.getBidder()+"</td></tr>"+
						"<tr><td style='width:150px;'>创建时间："+sdf.format(land.getDateCre())+"</td>"+
						"<td style='width:150px;'>创建人："+land.getUserCre()+"</td></tr>"+
						"<tr><td colspan='2'>备注："+land.getRemark()+"</td></tr>"
						+"</table>";
			}
			sb.append(sval+"*"+land.getMarkerName()+"#");
		}
		try {
			out = response.getWriter();
			response.setContentType("text/html;charset=gb2312");
			String s=sb.toString();
			s=s.substring(0,s.length()-1);
			out.print(s);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
